<template>
  <div class="app-container">
    <!-- <el-button type="text" @click="dialogVisible = true">添加</el-button> -->
    <!-- <el-card shadow="never"> -->
      <!-- <div slot="header" style="text-align: center;">店铺列表</div> -->
      <!-- 店铺店铺列表-->
      <el-button type="success" @click="addmodel">添加</el-button>
      <div class="tableClass">
        <el-table :data="formdata" v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          border style="width: 100%;">
          <el-table-column align="center" prop="id" label="序号" />
          <el-table-column align="center" prop="admin_name" label="管理员名称" />
          <el-table-column align="center" prop="username" label="账号">
            <template slot-scope="scope">
              <div>
                <span style="margin-right: 10px;">{{scope.row.username}}</span>
                <!-- <el-button size="mini" type="primary" @click="updatePaw">修改密码</el-button> -->
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="phone" label="手机号码" />
          <!-- <el-table-column align="center" prop="contact" label="密码" /> -->
          <el-table-column align="center" prop="role_name" label="角色">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.role_name !=null " effect="plain">{{scope.row.role_name}}</el-tag>
              <span v-else style="color: red;">暂无角色</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="status" label="状态">
            <template slot-scope="scope">
              <el-select v-model="scope.row.status" @change="changAdminStatus(scope.row.id)">
                <el-option v-for="opt in options" :key="opt.id" :value="opt.id" :label="opt.label" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="230px">
            <template slot-scope="scope">
              <!-- scope.row 获取整行信息 表示当前单元格 #ff9900ba-->
              <el-button class="btnAppeal" size="small" type="warning" @click="updateMsg(scope.row)">修改</el-button>
              <el-button class="btnAppeal" size="small" type="danger" @click="delMsg(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br>
        <!-- 分页 -->
        <div style="text-align: center;">
          <el-pagination background layout="prev, pager, next" @current-change="pageChange" :page-size="pageSize"
            :total="totalusers" />
        </div>
      </div>
    <!-- </el-card> -->



    <!-- 添加模态款 -->
    <el-dialog :title="title" :visible.sync="modelMsg">
      <div class="msgDiv">
        <!-- <h3>店铺基础信息</h3> -->
        <div>
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item v-show="vshow" label="序号">
              <el-input v-model="form.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="管理名称" :required="true">
              <el-input v-model="form.admin_name" placeholder="请输入管理员名称"></el-input>
            </el-form-item>
            <el-form-item label="号码" :required="true">
              <el-input v-model="form.phone" placeholder="请输入管理员手机号码"></el-input>
            </el-form-item>
            <el-form-item label="账号" :required="true">
              <el-input v-model="form.username" placeholder="请输入账号"></el-input>
            </el-form-item>
            <div v-if="form.id<=0">
              <el-form-item label="密码" :required="true">
                <el-input v-model="form.password" placeholder="请输入密码"></el-input>
              </el-form-item>
              <el-form-item label="确认密码" :required="true">
                <el-input v-model="checkPassword" placeholder="请再次输入密码"></el-input>
              </el-form-item>
            </div>
            <el-form-item label="状态" :required="true" style="text-align: left;line-height: 40px;">
              <el-select v-model="form.status">
                <el-option v-for="opt in options" :key="opt.id" :value="opt.id" :label="opt.label" />
              </el-select>
            </el-form-item>
            <el-form-item label="选择角色" :required="true">
              <div style="text-align: left;">
                <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                <el-checkbox-group v-model="checkedRoles" @change="CheckedRolesChange">
                  <el-checkbox v-for="role in rolesList" :key="role.id" :label="role">
                    {{ role.display_name }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </el-form-item>

          </el-form>
          <el-button type="success" @click="addMsg(form)">{{addORupdate}}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        modelMsg: false,

        form: {
          id: "",
          admin_name: "",
          username: "",
          password: "",
          phone: "",
          status: "0",
          role_id: []
        },
        checkPassword: "",
        options: [{
          id: '0',
          label: "关闭"
        }, {
          id: '1',
          label: "开启"
        }],
        vshow: false,
        loading: false,
        rolesList: [],
        checkedRoles: [],
        checkAll: false,
        title: "",
        addORupdate: "",
        formdata: [],
        totalusers: 0, //总行数
        pageSize: 5, //每页几行
        startpage: 1, //起始页
      }
    },
    mounted() {
      this.adminList()
      this.roleList()
    },
    methods: {
      //手动改变状态
      changAdminStatus(id) {
        let params = {
          "id": id
        }
        this.$api.changeAdminStatus(params).then(res => {
          console.log(res)
          this.$message({
            type: res.data.level,
            message: res.data.message
          });
          this.adminList()
        })
      },
      /* 全选权限 */
      handleCheckAllChange(val) {
        // 判断数组是否有相同数字或字符，有返回true。正则表达式
        Array.prototype.in_array = function(e) {
          var r = new RegExp(',' + e + ',')
          return (r.test(',' + this.join(this.S) + ','))
        }
        /* 三元表达式 */
        this.checkedRoles = val ? this.rolesList : []
        for (let i = 0; i < this.checkedRoles.length; i++) {
          const roleid = this.checkedRoles[i].id
          // 判断权限数组里是否存在相同的ID,为true跳出判断，不能用return，不然会跳出循环。为false追加进权限数组里
          const ss = this.form.role_id.in_array(roleid)
          if (ss === true) {
            continue
          } else {
            this.form.role_id.push(roleid)
          }
        }
        // 假设val为true(全选状态)，就把权限ID追加（push）进role_id[]数组里；否则为空
        this.form.role_id = val ? this.form.role_id : []
      },

      /* 单选 */
      CheckedRolesChange(value) {
        //选中的值
        this.checkedRoles = value
        // 判断假如单选的长度与权限列表长度一致则为true显示勾，否则为false
        const checkedCount = value.length
        this.checkAll = checkedCount === this.rolesList.length
        // 点击单选时，判断选择的权限数组里是否存在这个id,没有则添加，取消钩子要从数组里删除该权限
        const roleid = []
        for (let i = 0; i < value.length; i++) {
          roleid.push(value[i].id)
        }
        this.form.role_id = roleid
      },
      //获取角色列表
      roleList() {
        let params = {
          "page": 1,
          "limit": 100000
        }
        this.$api.roleList(params).then(res => {
          console.log(res)
          if(res.data.level=="success"){
            this.rolesList = res.data.data
          }else{
            this.$message.error(res.data.message)
          }
        })
      },
      //获取分页列表
      adminList() {
        this.formdata = []
        let params = {
          "page": this.startpage,
          "limit": this.pageSize
        }
        //调用后台提供的接口方法
        this.$api.adminList(params).then(res => {
          if (res.data.level == "success") {
            this.formdata = res.data.data
            this.totalusers = res.data.page_info.total
            this.loading = false
          }else{
            this.$message.error(res.data.message)
            this.loading = false
          }

        })
      },
      //分页 pageChange当前页发生改变触发函数
      async pageChange(page) {
        this.startpage = page
        this.loading = true
        //调用获取列表的方法
        this.adminList()
      },
      addmodel() {
        this.modelMsg = true
        this.title = '添加管理员信息'
        this.addORupdate = "添加",
          this.vshow = false
        this.form.id = "",
          this.form.admin_name = "",
          this.form.username = "",
          this.form.password = "",
          this.checkPassword = "",
          this.form.phone = "",
          this.form.status = "0",
          this.form.role_id = []
        this.checkedRoles = []
        this.checkAll = false
      },
      //提交店铺入驻申请
      async addMsg(form) {
        //判断带星号的是否为空
        if ((form.admin_name && form.username && form.username && form.status) == "") {
          this.$message({
            message: "带星号为必填项，请完善信息！",
            type: "warning"
          })
          return false;
        }

        if (form.id > 0) {
          /* 修改 */
          /* 显示加载中。。。 */
          const loadingOne = this.$loading({
            lock: true,
            text: '保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          console.log(form)
          await this.$api.setAdmin(form).then(res => {
            console.log(res)
            this.$message({
              type: res.data.level,
              message: res.data.message
            });
            if (res.data.level == "success") {
              this.adminList()
              loadingOne.close()
              this.modelMsg = false
            } else {
              this.modelMsg = true
              loadingOne.close()
            }

          })
        } else {
          if (form.password == "") {
            this.$message({
              message: "带星号为必填项，请完善信息！",
              type: "warning"
            })
            return false;
          }
          let pwd = form.password;
          let pwdCheck = this.checkPassword;
          if (pwd != pwdCheck) {
            this.$message({
              message: "两次输入密码不匹配！",
              type: "warning"
            })
            return false;
          }
          /* 显示加载中。。。 */
          const loadingOne = this.$loading({
            lock: true,
            text: '保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          /* 添加 */
          await this.$api.setAdmin(form).then(res => {
            this.$message({
              type: res.data.level,
              message: res.data.message
            });
            if (res.data.level == "success") {
              this.adminList()
              loadingOne.close()
              this.modelMsg = false
            } else {
              loadingOne.close()
              this.modelMsg = true
            }

          })
        }

      },
      //修改弹出框
      async updateMsg(row) {
        console.log(row)
        console.log(this.form.classify_id)
        console.log(this.form.classify_name)
        this.modelMsg = true
        this.title = '修改管理员信息'
        this.addORupdate = "修改",
          this.vshow = true
        this.form.id = row.id,
          this.form.username = row.username,
          this.form.admin_name = row.admin_name,
          this.form.phone = row.phone,
          this.form.status = row.status

        const dataid = {
          'id': row.id
        }
        let roleids = []
        await this.$api.adminSet(dataid).then(res => {
          console.log(res)
          roleids = res.data.data.role_id
        })

        // 判断查询出来的角色权限的长度是否等于所有权限列表，相等则checkAll为true，勾选全选状态，否则勾选已有的几项
        if (roleids.length === this.rolesList.length) {
          this.checkAll = true
          this.handleCheckAllChange(true)
        } else {
          console.log('查询出来的角色权限的长度不等于所有权限列表，并且不勾选全部')
          this.checkAll = false
          this.handleCheckAllChange(false)
          const roleObj = []
          // 根据更新设入的权限id数组并遍历出来和遍历出总权限数组，两个通过冒泡排序方式对比，有相等的id赋值给复选框进行勾选
          for (let j = 0; j < roleids.length; j++) {
            for (let i = 0; i < this.rolesList.length; i++) {
              const rolesListid = this.rolesList[i].id
              if (roleids[j] === rolesListid) {
                roleObj.push(this.rolesList[i])
                this.CheckedRolesChange(roleObj)
              }
            }
          }

        }
      },
      //删除店铺信息
      async delMsg(id) {
        let delid = {
          id: id
        }
        await this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const loadingOne = this.$loading({
            lock: true,
            text: '保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.$api.delAdmin(delid).then(res => {
            if (res.data.level == "success") {
              this.$message.success(res.data.message)
              loadingOne.close()
              this.adminList()
            } else {
              this.$message.error(res.data.message)
              loadingOne.close()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });


      }
    }
  }
</script>
<style scoped="scoped">
  /deep/.el-card__header {
    background-color: #409EFF;
    color: whitesmoke;
  }

  /deep/.el-dialog {
    margin-top: 10vh !important;
    width: 33%;
  }

  .msgDiv {
    width: 80%;
    margin: auto;
    text-align: center;
  }

  .el-input {
    display: flex;
    flex-grow: <2>;
  }
</style>
